<!--
 * @description  : 证件-依职权办理审批表
 * @descriptionDetail: 证件-依职权办理审批表
 * @copyright    : 浙江烟草
 * @author       : sy
 * @create       : 2022-07-18 15:29:13
-->
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :isWhite="true" backText="返回" title="依职权办理审批表"></theme-navbar>
    <!-- #endif -->

    <view class="content">
      <u-form
        :label-style="labelStyle"
        :error-type="errorType"
        :rules="rules"
        :label-width="labelWidth"
        :model="applyData"
        ref="uForm"
        label-position="top"
      >
        <u-form-item label="办理事项" :label-style="fontStyle">
          <view>
            {{ applyData.applyTypeName }}
          </view>
        </u-form-item>
        <!-- 折叠面板信息 -->
        <view>
          <u-collapse ref="athCL">
            <u-collapse-item @change="changePage">
              <view class="basc-font" slot="title">
                持证人基本信息<text class="u-font-26">
                  （点击查看详情）
                </text>
              </view>
              <u-form-item label="许可证号">
                <view class="zk-disabled">
                  {{ applyData.licNo }}
                </view>
              </u-form-item>
              <u-form-item label="经营者/法定代表人(负责人)">
                <view class="zk-disabled">
                  {{ applyData.managerName }}
                </view>
              </u-form-item>
              <u-form-item label="企业【字号】" label-width="170">
                <view class="zk-disabled">
                  {{ applyData.companyName }}
                </view>
              </u-form-item>
              <u-form-item label="经营范围" label-width="150">
                <view class="zk-disabled">
                  {{ applyData.managerScopeName }}
                </view>
              </u-form-item>
              <u-form-item label="许可证有效期" label-width="170">
                <view class="zk-disabled">
                  {{ applyData.validBeginDate }} 至 {{ applyData.validEndDate }}
                </view>
              </u-form-item>
              <u-form-item label="经营地址" label-width="160">
                <view class="zk-disabled">
                  {{ applyData.businessAddr }}
                </view>
              </u-form-item>
              <u-form-item label="经济类型">
                <view class="zk-disabled">
                  {{ applyData.ecoTypeName }} {{ applyData.ecoSubTypeName || "" }}
                </view>
              </u-form-item>
              <u-form-item label="群体类型">
                <view class="zk-disabled">
                  {{ applyData.specialGroupTypeName }}
                </view>
              </u-form-item>
              <u-form-item label="场地权属">
                <view class="zk-disabled">
                  {{ applyData.groundOwnershipTypeName }}
                </view>
              </u-form-item>
              <u-form-item label="租赁（无偿使用）期限" label-width="240">
                <view class="zk-disabled">
                  {{ applyData.tenancyBeginDate }} 至 {{ applyData.tenancyEndDate }}
                </view>
              </u-form-item>
              <u-form-item label="证件类型及号码" label-width="200">
                <view class="zk-disabled">
                  {{ applyData.managerIdCardTypeName }} {{ applyData.managerIdCardNo }}
                </view>
              </u-form-item>
              <u-form-item label="证件登记地址" label-width="170">
                <view class="zk-disabled">
                  {{ applyData.managerIdCardAddr }}
                </view>
              </u-form-item>
              <u-form-item label="现居地" label-width="150">
                <view class="zk-disabled">
                  {{ applyData.managerNowAddr }}
                </view>
              </u-form-item>
            </u-collapse-item>
          </u-collapse>
        </view>
        <!-- 责令停业整顿显示  -->
        <view v-if="applyData.applyType == 'L0110'">
          <u-form-item
            :required="isRequired"
            label="责令整顿(起始)期限"
            right-icon="arrow-right"
            prop="closedBeginDate"
            ref="startChangeRef"
          >
            <u-input
              placeholder="请选择日期"
              input-align="right"
              :disabled="true"
              :custom-style="valueStyle"
              v-model="closedBeginDate"
              @click="clicDatekHandle('isShowCyBegin')"
            />
          </u-form-item>
          <u-form-item
            :required="isRequired"
            label="责令整顿(截止)期限"
            right-icon="arrow-right"
            prop="closedEndDate"
            ref="endChangeRef"
          >
            <u-input
              placeholder="请选择日期"
              input-align="right"
              :disabled="true"
              :custom-style="valueStyle"
              v-model="closedEndDate"
              @click="clicDatekHandle('isShowCyEnd')"
            />
          </u-form-item>
          <u-form-item
            label="办理依据"
            :label-width="labelWidth"
            :required="isRequired"
            prop="approveFact"
            :label-position="labelPosition"
            right-icon="arrow-right"
          >
            <u-input :border="border" type="textarea" :select-open="factTypeShow" placeholder="请选择" v-model="applyData.approveFact" @click="factTypeShow = true"></u-input>
          </u-form-item>
        </view>
        <!-- 责令变更显示 -->
        <view v-if="applyData.applyType == APPLAP_TYPE.ORDER_CHANGE">
          <u-form-item
            label="责令变更项"
            right-icon="arrow-right"
            :required="isRequired"
            prop="orderChangeItemName"
            ref="orderChangeRef"
            label-position="top"
          >
            <u-input
              :disabled="true"
              type="textarea"
              placeholder="请选择责令变更项"
							:custom-style="valueStyle"
              v-model="applyData.orderChangeItemName"
              @click="selectChangeItems"
            ></u-input>
          </u-form-item>
        </view>
        <!-- 承办人 -->
        <view>
          <u-form-item label="承办人意见" :label-style="fontStyle"></u-form-item>
          <u-form-item
            :label-width="labelWidth"
            label="建议责令整顿"
            :required="isRequired"
            prop="decideIsPass"
            v-if="applyData.applyType == APPLAP_TYPE.STOP_RECTIFY"
          >
            <u-switch
              :disabled="isDisabled"
              slot="right"
              v-model="applyData.decideIsPass"
              @change="switchChange($event,'decideIsPass','transDecide')"
            ></u-switch>
          </u-form-item>
          <u-form-item :label-position="labelPosition" prop="transDecide">
            <u-input
              type="textarea"
              :border="true"
              placeholder="请填写承办人意见"
              :disabled="isDisabled"
              v-model="applyData.transDecide"
            />
          </u-form-item>
          <u-form-item>
            <view class="per-desc">
              <u-icon
                :label="applyData.transPersonName"
                size="24"
                name="man-add"
                label-color="#999"
                label-size="24"
              ></u-icon>
              <text class="per-title">
                {{ applyData.transTime }}
              </text>
            </view>
          </u-form-item>
        </view>
      </u-form>
      <view class="gap-space"></view>
    </view>
    <!-- 底部按钮 -->
    <view class="submit-btns btn-other-cls">
      <u-button
        plain
        type="primary"
        class="u-btn"
        v-if="!docIns.step || docIns.step == 'edit'"
        @click="submitAudit('save')"
      >
        保存
      </u-button>
      <u-button
        type="primary"
        class="u-btn"
        v-if="!docIns.step || docIns.step == 'edit'"
        @click="submitAudit('submit')"
      >
        提交
      </u-button>
      <u-button
        type="primary"
        class="u-btn"
        v-if="!!docIns.step && docIns.step != 'edit'"
        @click="downloadFile"
      >
        打印
      </u-button>
    </view>
    <!-- 责令变更项 -->
    <u-popup mode="bottom" border-radius="14" height="80%" v-model="layoutShow">
      <multi-select :options="layoutOptions" :defaultUids="defaultUids" @select="handlerSelectlayout">
      </multi-select>
    </u-popup>
    <!-- 办理依据 -->
    <u-popup mode="bottom" height="80%" border-radius="14" v-model="factTypeShow">
      <single-select :extHide="true" :isWrap="true" :title="'办理依据'" :selectedData="{uid:applyData.approveFactType,name:applyData.approveFact}" :mDatas="clauseList" @m-select="selectTypeConfirm"></single-select>
    </u-popup>
    <!-- 数据字典 -->
    <dic-choice
      :keyWord="dicKeyWords"
      :currentSelect="dicCurrentSelect"
      v-model="dicShow"
      @confirm="selectDicConfirm"
    ></dic-choice>
    <u-calendar
      :mode="mode"
      :min-date="minDate"
      :max-date="maxDate"
      v-model="isShowCyBegin"
      @change="changeDate('closedBeginDate',$event)"
    >
    </u-calendar>
    <u-calendar
      :mode="mode"
      :max-date="maxDate"
      :min-date="closedBeginDate"
      v-model="isShowCyEnd"
      @change="changeDate('closedEndDate',$event)"
    >
    </u-calendar>
  </view>
</template>

<script>
import DicChoice from "@/components/dic_choice.vue";
import DicInput from "@/components/dic_input.vue";
import SingleSelect from "@/components/single-select.vue";
import certificateService from "@/service/certificate/certificate.service.js";
import multiSelect from '@/components/multi-select.vue';
import commonService from "@/service/common/common.service.js";
import { LOG_STATUS, LOG_OP_TYPE, } from '@/service/common/mapping/enum.js';
import { APPLAP_TYPE, } from "@/service/check/mapping/enum.js";
export default {
  components: {
    "dic-choice": DicChoice,
    "single-select": SingleSelect,
    multiSelect,
  },
  props: {

  },
  data() {
    return {
      APPLAP_TYPE,
      border: false,
      fontStyle: {
        fontWeight: 'bold',
      },
      labelPosition: 'top',
      labelStyle: {
        // color: '#333',
        fontSize: '26rpx',
      },
      rightIconStyle: {
        'fontSize': '40rpx',
        'color': this.$theme.u_type_primary,
      },
      beginTime: "",
      dicShow: false, // dic_select 是否显示
      dicKeyWords: "", // dic 关键字
      dicCurrentSelect: "", // dic 当前选择项
      labelWidth: '360',
      mode: 'date',
      maxDate: '2099-12-31',
      minDate: this.$u.timeFormat(Date.now()),
      closedBeginDate: '',
      closedEndDate: '',
      errorType: ['border-bottom', 'message',],
      // athForm:{},
      isShowCyBegin: false,
      isShowCyEnd: false,
      isRequired: true,
      isDisabled: false,
      athApForm: {},
      applyData: {},
      nextPersons: [],
      userInfo: this.$storage.get(this.$rp.common.USER).user,
      preParams: {}, // 上个页面传过来的参数
      docIns: {},
      layoutShow: false,
      layoutOptions: [],
      defaultUids: [],
      dictType: 'L_ORDER_CHANGE_ITEM',
      // 校验规则
      rules: {
        orderChangeItemName: [{
          required: true,
          message: '请选择责令变更项',
          trigger: ['change', 'blur',],
        },],
        transDecide: [{
          required: true,
          message: '请填写承办人意见',
        }, {
          max: 200,
          message: '承办人意见不能超过200个字',
          trigger: 'change',
        },],
        approveFact: [{
          required: true,
          message: '请选择办理依据',
          trigger: 'change',
        },],
        closedBeginDate: [{
          required: true,
          message: '请选择责令整顿(起始)期限',
          trigger: ['change', 'blur',],
        },],
        closedEndDate: [{
          required: true,
          message: '请选择责令整顿(截止)期限',
          trigger: ['change', 'blur',],
        }, {
          validator: () => {
            return this.closedEndDate < this.closedBeginDate ? false : true;
          },
          message: '(截止)期限必须大于(起始)期限',
        },],
      },
      clauseList: [], // 办理依据
      factTypeShow: false,
			// h5端部分浏览器input设置disabled后点击事件失效 2023-10-25 fsx start
			valueStyle: {
			  marginRight: "5px",
				pointerEvents: "none !important"
			},
			// h5端部分浏览器input设置disabled后点击事件失效 2023-10-25 fsx end
    };
  },
  watch: {
    isShowCyBegin(newValue, oldValue) {
      this.$refs.startChangeRef.validation();
    },
    isShowCyEnd(newValue, oldValue) {
      this.$refs.endChangeRef.validation();
    },
  },
  created() {
    // 合理布局dict初始化
    commonService.bscCodesMap(this.dictType).then(dr => {
      if (dr.success) {
        let ps = dr.bean[this.dictType];
        ps.map(p => {
          p.uid = p.bcbCode;
          p.name = p.bcbName;
          p.exts = [p.bcbCode, p.bcbName,];
        });
        this.$nextTick(() => this.layoutOptions = ps);
      }
    });
  },
  onLoad() {
    this.preParams = this.getRouteParam();
    this.initApplyData();
    // 停业整顿'L0110'
    if(this.preParams.applyType == APPLAP_TYPE.STOP_RECTIFY){
      this.initClause();
    }

  },
  mounted() {
    this.$refs.uForm.setRules(this.rules);
  },
  methods: {
    changePage() {
      this.$nextTick(function () {
        this.$refs['athCL'].init();
      });
    },
    // 获取办理依据
    initClause() {
      this.clauseList = [];
      certificateService.getClauseCodes({ applyType: this.preParams.applyType, docCode: "docAuthApproveCancel", }).then((res) => {
        if (res.success) {
          res.data.forEach((item) => {
            this.clauseList.push({ uid: item.caseId, name: item.caseName, });
          })
        }
      }).catch((err) => {
        this.$u.toast(err);
      })
    },
    // 办理依据选择事件
    selectTypeConfirm(e) {
      this.applyData.approveFact = e.name;
      this.applyData.approveFactType = e.uid;
      this.factTypeShow = false;
    },
    // 数据字典组件选择事件
    dicSelectOpen: function (keyWords) {
      if (this.dicKeyWords == keyWords && this.dicShow) {
        return true;
      }
      return false;
    },
    showDic: function (key, cur) {
      if (this.dicShow) return;
      this.dicKeyWords = key;
      this.dicCurrentSelect = cur;
      this.dicShow = true;
    },
    selectDicConfirm: function (e) {
      // 类型
      if (this.dicKeyWords == this.$u.dic.DIC_KEYS.FACT) {
        this.applyData.approveFactName = e[0].label;
        this.applyData.approveFactType = e[0].extra.bcbCode;
      }
    },
    // 初始化数据
    initApplyData() {
      if (this.preParams['docInsUuid']) {
        // 文书实例信息
        certificateService.getDocIns(this.preParams.docInsUuid).then(dr => {
          this.docIns = dr.bean;
          this.isDisabled = this.docIns.step != 'edit';
          // 承办人意见，流程信息
          Promise.all([
            certificateService.getAuthDoc({
              id: this.docIns.docInsUuid,
              docUuid: this.docIns.docUuid,
              bizUuid: this.docIns.bizUuid,
            }),
            certificateService.approves({
              id: this.docIns.docInsUuid,
              docUuid: this.docIns.docUuid,
            }),
          ]).then(res => {
            this.applyData = res[0].data[0];
            // 日期处理
            this.closedEndDate = this.applyData.closedEndDate;
            this.closedBeginDate = this.applyData.closedBeginDate;
          });
        });
      } else {
        certificateService.getBaseInfoOneByLicNo({ applyType: this.preParams.applyType, licNo: this.preParams.licNo, })
          .then(res => {
            if (res.success) {
              let [licInfo, self,] = [res.bean, this,];
              this.initLicInfo(licInfo);
              // 默认数据
              this.$u.dic.getDicNameByDDextCode(this.preParams.applyType, "L_APPLY_TYPE")
                .then(
                  (res2) => {
                    self.$set(self.applyData, 'applyTypeName', res2.bcbName);
                  },
                );
              this.applyData.applyType = this.preParams.applyType;
              this.applyData.transTime = this.$u.date(Date.now(), "yyyy年mm月dd日");
              this.applyData.transPersonName = this.userInfo.personName;
              this.applyData.transPersonUuid = this.userInfo.personUuid;
              // 默认建议责令整顿'L0110'
              if (this.preParams.applyType == APPLAP_TYPE.STOP_RECTIFY) {
                this.applyData.decideIsPass = true;
                this.applyData.transDecide = "建议责令整顿";
              }
              this.applyData.caseUuid = this.preParams.checkUuid;
            } else {
              this.$u.toast(res.msg);
              setTimeout(() => {
                this.backPrev({
                  paramKey: 'refreshCheck',
                  param: true,
                });
              }, 2000);
            }
          });
      }
    },
    // 初始化零售户基础信息person, rData
    initLicInfo(lic) {

      /* 从许可证信息接口中转换部分数据 */
      let turnMap = new Map([
        ["licNo", "licNo",],
        ["companyName", "companyName",],
        ["managerName", "managerName",],
        ["managerScope", "managerScope",],
        ["managerScopeName", "managerScopeNm",],
        ["validBeginDate", "validateStart",],
        ["businessAddr", "businessAddr",],
        ["validEndDate", "validateEnd",],
        ["businessAdc", "areaCode",],

        ["groundOwnershipType", "groundOwnership",],
        ["groundOwnershipTypeName", "groundOwnershipNm",],
        ["tenancyBeginDate", "leaseTimelimitStart",],
        ["tenancyEndDate", "leaseTimelimitEnd",],
        ["businessAddrStreet", "businessAddr",],
        ["ecoType", "ecoType",],
        ["ecoTypeName", "ecoTypeNm",],
        ["ecoSubType", "ecoSubType",],
        ["ecoSubTypeName", "ecoSubTypeNm",],
        ["specialGroupType", "specialType",],
        ["specialGroupTypeName", "specialTypeNm",],
        ["specialGroupTypeOther", "specialTypeOther",],
        ["closedBeginDate", "applyCloseStart",],
        ["closedEndDate", "applyCloseEnd",],
        ["managerIdCardType", "managerCredType",],
        ["managerIdCardTypeName", "managerCredTypeNm",],
        ["managerIdCardNo", "managerCredNum",],
        ["managerIdCardAddrAdc", "",],
        ["managerIdCardAddrStreet", "managerCredAddr",],
        ["managerNowAdc", "",],
        ["managerNowAddr", "managerCurrentAddr",],
        ["managerIdCardAddr", "managerCredAddr",],
      ]);
      turnMap.forEach((v, k) => {
        this.$set(this.applyData, k, lic[v]);
      });
      // 日期处理
      this.closedEndDate = this.applyData.closedEndDate;
      this.closedBeginDate = this.applyData.closedBeginDate;
      this.changePage();
    },
    // 日期处理
    clicDatekHandle(type) {
      if (this.isDisabled) return;
      this[type] = true;
    },
    changeDate(type, e) { //
      this[type] = e.result;
      this.applyData[type] = this.$u.date(new Date(e.result).getTime(), 'yyyy年mm月dd日');
    },
    // 选择责令变更项
    selectChangeItems() {
      if (this.isDisabled) return;
      this.layoutShow = true;
    },
    // 选择变更项
    handlerSelectlayout(pItems) {
      this.layoutShow = false;
      let [ns, items, self,] = [
        [],
        [], this,
      ];
      pItems.forEach((_item) => {
        items.push(_item.bcbCode);
        ns.push(_item.bcbName);
      });
      self.$set(self.applyData, 'orderChangeItem', items.join(","));
      self.$set(self.applyData, 'orderChangeItemName', ns.join(","));
      this.defaultUids = items;
      this.$refs.orderChangeRef.validation();
    },
    // 数据返回操作
    updateBackState(obj) {
      if (obj.flowUserSelectBack) { // 选择审批人
        let nextPersons = [];
        let docUuid = this.preParams.applyType == APPLAP_TYPE.STOP_RECTIFY ? "65d3ca2da2ba4ad327f9a932a9214b13" :
          "65d3ca2da2ba4ad327f81832a9211123";
        for (let fu of obj.flowUserSelectBack) {
          nextPersons.push(fu.personId);
        }
        this.doSubmit(docUuid, nextPersons.join(","));
      }
    },
    // 提交、保存数据
    submitAudit(type) {
      let self = this;
      if (!this.validForm()) return;
      let docUuid = this.preParams.applyType == APPLAP_TYPE.STOP_RECTIFY ? "65d3ca2da2ba4ad327f9a932a9214b13" :
        "65d3ca2da2ba4ad327f81832a9211123";
      this.$modal.showLoading(`数据${type === "submit" ? '提交' : '保存'}中...`);
      certificateService.saveAuthDoc(this.applyData, docUuid, '', 'edit').then(dr => {
        self.$modal.hideLoading();
        if (dr.success) {
          // 保存后重新赋值“办理依据”
          let orderChangeItemNameOld = this.applyData.orderChangeItemName;
          this.applyData = dr.bean;
          this.applyData.orderChangeItemName = orderChangeItemNameOld;
          // 办理依据
          if (!this.$u.test.isEmpty(this.applyData.approveFactType)) {
            this.$u.dic.getDicNameByDDextCode(this.applyData.approveFactType, this.$u.dic.DIC_KEYS
              .FACT).then(
                (res) => {
                  self.$set(self.applyData, 'approveFactName', res.bcbName);
                },
              );
          }
          // 日期处理
          this.closedEndDate = this.applyData.closedEndDate;
          this.closedBeginDate = this.applyData.closedBeginDate;
          this.docIns = dr.data[0];
          if (type === 'submit') {
            this.$modal.confirm("请确认当事人姓名(名称)、身份证件信息是否正确，此数据一经提交将推送国家互联网+监管系统", () => {
              // 选择审批人
              this.$u.route({
                url: "/pages/commonPage/flowUserSelectComponent",
                params: {
                  flowFormCode: 'docAuthApprove',
                  docInsUuid: '',
                },
              });
            });
          } else {
            this.$u.toast("保存成功");
          }
        } else {
          this.$u.toast(dr.msg);
        }
      });
    },
    // 提交
    doSubmit(docUuid, nextPersons) {
      let self = this;
      this.$modal.showLoading('数据提交中...');
      certificateService.submitAuthDoc(this.applyData, docUuid, this.docIns.docInsUuid, "", this.docIns.step,
        nextPersons).then(auth => {
          self.$modal.hideLoading();
          if (auth.success) {
            certificateService.getDocIns(this.docIns.docInsUuid).then(doc => {
              this.docIns = doc.bean;
              this.isDisabled = this.docIns.step != 'edit';
            });
            this.nextClick();
          } else {
            this.$u.toast(auth.msg);
          }
        }).catch(err => {
          self.$modal.hideLoading();
          this.$u.toast(err);
        });
    },
    // switch开关
    switchChange(status, type, desc) {
      this.applyData[type] = status;
      this.applyData[desc] = !status ? '不建议责令变更' : "建议责令变更";
    },
    // 表单校验
    validForm() {
      let confirmValid = false;
      this.$refs.uForm.validate(valid => {
        if (valid) {
          confirmValid = true;
        } else {
          confirmValid = false;
        }
      });
      return confirmValid;
    },
    nextClick() {
      // 返回到检查详情页面
      this.backPrev({
        paramKey: 'refreshCheck',
        param: true,
      });
    },
    // 打印
    downloadFile() {
      if (!this.docIns.pdfFileId) {
        this.$u.toast("没有文书");
        return;
      }
      this.setRouteParam({
        fileId: this.docIns.pdfFileId,
      });
      this.$u.route('pages/commonPage/printerComponent');
    },
    /**
   * @param {Boolean} status 提交还是保存
   */
    saveBehaviorLog(status, doc) {
      commonService.getCurrentTime().then(res2 => {
        let param = {
          bizUuid: doc.bizUuid,
          docUuid: doc.docUuid,
          docInsUuid: doc.docInsUuid,
          bizType: LOG_STATUS.B007,
          operationType: status == 0 ? LOG_OP_TYPE.saveDoc : LOG_OP_TYPE.submitDoc,
          beginTime: this.beginTime,
          endTime: res2.success ? res2.msg : this.$u.timeFormat(Date.now(), 'yyyy-mm-dd hh:MM:ss'),
          remark: doc.configIns.docName,
        };
        this.beginTime = param.endTime;
        commonService.saveBehaviorLog(param).then(res => {
          console.log(res);
        }).catch(e => {
          console.log(e);
        });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "style/certificate/common.scss";

.page {
  padding: 0;
}

.desc-btm {
  font-size: 13px;
  color: #333;
}

/deep/.u-form-item {
  line-height: 28px;
}

.basc-font {
  font-weight: 600;
  font-size: 15px;
}

.per-desc {
  font-size: 13px;
  color: #999;
  margin-right: 20px;

  .per-title {
    padding-left: 20px;
  }
}

/deep/.u-input--border {
  min-height: 160px;
}
</style>
